package ltd.newbee.mall.util;

import org.apache.commons.codec.digest.DigestUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;

/**
 * 顺丰API工具类
 */
public class SfApiUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 生成数字签名
     */
    public static String generateMsgDigest(String msgData, long timestamp, String checkWord) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //客户校验码    使用顺丰分配的客户校验码


        //将业务报文+时间戳+校验码组合成需加密的字符串(注意顺序)
        String toVerifyText = msgData + timestamp + checkWord;

        //因业务报文中可能包含加号、空格等特殊字符，需要urlEnCode处理
        try {
            toVerifyText = URLEncoder.encode(toVerifyText, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        //进行Md5加密
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(toVerifyText.getBytes("UTF-8"));
        byte[] md = md5.digest();

        //通过BASE64生成数字签名
        String msgDigest = Base64.getEncoder().encodeToString(md);
        return msgDigest;

    }

    /**
     * 生成UUID请求ID
     */
    public static String generateRequestId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 对象转JSON字符串
     */
    public static String toJsonString(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("对象转JSON失败", e);
        }
    }

    /**
     * JSON字符串转对象
     */
    public static <T> T fromJsonString(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JSON转对象失败", e);
        }
    }
}
